package com.atom.module.mvvm.extren

import androidx.annotation.CheckResult
import androidx.appcompat.widget.SearchView
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate


@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
fun SearchView.queryTextChanges() = callbackFlow <CharSequence>{
    checkMainThread()
    val listener = object : SearchView.OnQueryTextListener {
        override fun onQueryTextChange(newText: String): Boolean {
            trySend(newText)
            return true
        }

        override fun onQueryTextSubmit(query: String): Boolean = false
    }
    setOnQueryTextListener(listener)
    awaitClose { setOnQueryTextListener(null) }
}
    .conflate()
    .asInitialValueFlow { query }


@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
fun SearchView.queryTextEvents()= callbackFlow<QueryTextXEvent> {
    checkMainThread()
    val listener = object : SearchView.OnQueryTextListener {
        override fun onQueryTextChange(newText: String): Boolean {
            trySend(
                QueryTextXEvent.QueryChanged(
                    view = this@queryTextEvents,
                    queryText = newText
                )
            )
            return true
        }

        override fun onQueryTextSubmit(query: String): Boolean {
            trySend(
                QueryTextXEvent.QuerySubmitted(
                    view = this@queryTextEvents,
                    queryText = query
                )
            )
            return true
        }
    }
    setOnQueryTextListener(listener)
    awaitClose { setOnQueryTextListener(null) }
}
    .conflate()
    .asInitialValueFlow {
        QueryTextXEvent.QueryChanged(
            view = this,
            queryText = query
        )
    }


sealed class QueryTextXEvent {
    abstract val view: SearchView
    abstract val queryText: CharSequence

    data class QueryChanged(
        override val view: SearchView,
        override val queryText: CharSequence
    ) : QueryTextXEvent()

    data class QuerySubmitted(
        override val view: SearchView,
        override val queryText: CharSequence
    ) : QueryTextXEvent()
}

